/**
 * @desc 日志中间件
 */
import { Request, Response, NextFunction } from 'express';
import fs from 'fs';

/**
 * 格式化信息
 * @param req 请求信息
 */
const formatLogInfo = (req: Request) => {
  return `[${new Date(Date.now()).toLocaleString()}] ----- url: ${req.url}, method: ${req.method}, body: ${JSON.stringify(req.body)}, query: ${JSON.stringify(req.query)}, statusCode: ${req.statusCode}, baseUrl: ${req.baseUrl}, header: ${JSON.stringify(req.header)}\n`;
}

/**
 * 错误日志
 */
export const ErrLogger = (obj: any) => {
  fs.appendFile('./logger/err.txt', JSON.stringify(obj) ,(err)=>{
    if(err) throw err;
  });
}

/**
 * 支付日志
 */
export const PayListLogger = (obj: any) => {
  fs.appendFile('./logger/pay.txt', JSON.stringify(obj) ,(err)=>{
    if(err) throw err;
  });
}

/**
 * 请求日志中间件
 */
export const logger = (req: Request, res: Response, next: NextFunction) => {
  const log = formatLogInfo(req);
  fs.appendFile('./logger/log.txt', log ,(err)=>{
    if(err) throw err;
  });
  next();
}